package net.wsnetwork.jawa.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.regex.Matcher;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.HeaderGroup;

public abstract class HttpConnectionHandler implements ConnectionHandler {
    @Override public boolean handleConnection(InputStream in, OutputStream out) throws
    IOException, ConnectionProcessingException {
        BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
        String line;
        String uri = null;
        HeaderGroup headers = new HeaderGroup();
        while ((line = inReader.readLine()) != null) {
            if (line.toLowerCase().startsWith("get")) {
                int end = line.length() - 9;
                uri = line.substring(4, end);
            } else if (line.isEmpty()) {
                break;
            } else {
                Matcher headerMatcher = Constants.HEADER_PATTERN.matcher(line);
                if (headerMatcher.find()) {
                    Header header =
                        new BasicHeader(headerMatcher.group(1), headerMatcher.group(2));
                    headers.addHeader(header);
                }
            }
        }
        if (uri == null) {
            return false;
        }
        return handleHttpConnection(out, uri, headers);
    }

    protected abstract boolean handleHttpConnection(OutputStream out, String uri,
            HeaderGroup headers) throws IOException, ConnectionProcessingException;
}
